import sys
import json
import os
from PyQt5.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QPushButton,
    QHBoxLayout,
    QMessageBox,
    QMainWindow,
    QWidget,
    QApplication,
    QDesktopWidget,
)
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt


# 读取json文件
def read_json(jsonPath=""):
    if not os.path.exists(jsonPath):
        return None
    with open(jsonPath, "r", encoding="utf-8") as file:
        data = json.load(file)
    return data


class DlgModelParams(QDialog):
    onOK = pyqtSignal(dict, type(lambda x: x))
    _shown = False  # 类属性来跟踪对话框是否已显示
    _instance = None  # 用于保存对话框实例的类变量

    def __init__(self, parent=None):

        super().__init__(parent)
        self.parent_widget = parent  # 保存父控件的引用
        self.save_data = {}  # 添加一个变量存储返回值

        self.component = None

        self.vbox = QVBoxLayout(self)
        self.pBtnOK = QPushButton("保存")

        self.pBtnOK.setObjectName("pBtnOK")
        self.pBtnOK.clicked.connect(self.on_pBtnOK_clicked)
        self.pBtnOK.setFocusPolicy(Qt.NoFocus)

        self.pBtnCancel = QPushButton("取消")
        self.pBtnCancel.setObjectName("pBtnCancel")
        self.pBtnCancel.clicked.connect(self.close)
        self.pBtnCancel.setFocusPolicy(Qt.NoFocus)

        self.setMinimumWidth(500)

        self.btnLayout = QHBoxLayout()
        self.btnLayout.setContentsMargins(10, 15, 10, 0)  # 左, 上, 右, 下
        self.btnLayout.setAlignment(Qt.AlignCenter)
        self.btnLayout.addWidget(self.pBtnOK)
        self.btnLayout.addWidget(self.pBtnCancel)
        self.vbox.addLayout(self.btnLayout)
        self.setLayout(self.vbox)

    @classmethod
    def show(cls, parent=None):
        if cls._shown:
            cls._instance.activateWindow()
            cls._instance.raise_()
            cls._instance.disconnectCustomSignals()
            return cls._instance
            # return cls._instance
        else:
            cls._instance = cls(parent)  # 创建新实例并传入parent
            cls._instance.setParent(parent)  # 设置父窗口
            QDialog.show(cls._instance)  # 直接调用QDialog的show方法
            cls._shown = True
            return cls._instance

    def disconnectCustomSignals(self):
        for attr_name in dir(self):
            attr = getattr(self, attr_name)
            if hasattr(attr, "disconnect") and attr_name.endswith("_signal"):
                try:
                    attr.disconnect()
                except TypeError:
                    pass

    def closeEvent(self, event):
        pass

    def updateUi(self, data):
        self.component.updateUi(data)

    def updateUi2(self, data1, data2):
        self.component.updateUi(data1, data2)

    def updateUiTable(self, data):
        self.component.updateUiTable(data)

    def updateUiTable2(self, data1, data2):
        self.component.updateUiTable(data1, data2)

    def center_dialog(self):
        rect = self.parent_widget.frameGeometry()
        x = rect.center().x() - self.width() // 2
        y = rect.center().y() - self.height() // 2
        self.move(x, y)  # 移动对话框到计算出的位置
        # # 获取屏幕中心点的坐标
        # available_geometry = QDesktopWidget().availableGeometry()
        # center_point = available_geometry.center()

        # # 设置对话框位置为屏幕中心
        # self.move(center_point.x() - self.width() // 2, center_point.y() - self.height() // 2)

    @pyqtSlot(dict)
    def handle_before_save(self, data):
        """处理 before_save_signal 信号返回的数据"""
        self.save_data = data

    @pyqtSlot()
    def on_pBtnOK_clicked(self):
        # 触发保存前信号
        if self.component:
            # 连接信号到槽函数
            self.component.return_save_result_signal.connect(self.handle_before_save)
            # 发送信号
            self.component.before_save_signal.emit({})
            # 使用返回的数据
            return self.save_data
            # if self.save_data:
            #     # 验证通过，执行保存操作
            #     self.close()
            # print("保存前获取的数据:", self.save_data)
